package net.csdn.business.discuss.common.dto;


import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.collect.Lists;
import lombok.Getter;

import java.io.Serializable;
import java.util.List;

/**
 * @author liushuangyi
 * @Classname SuperPageRequestDTO
 * @Description TODO
 * @Date 2020/5/11 1:04 PM
 * @Version V1.0
 */
@Getter
public abstract class SuperPageQueryDTO<T> implements Serializable {

    /**
     * 页码
     */
    protected Integer page = 1;

    /**
     * 每页大小
     */
    protected Integer size = 10;


    /**
     * 排序,调用示例:&sorts=id,asc&sorts=tenant_id,desc
     */
    protected List<PageSort> sorts = Lists.newArrayList();

    public Page<T> getPage() {
        Page<T> pagination = new Page<>(page, size);
        //设置排序类型
        List<OrderItem> list = Lists.newArrayList();
        this.sorts.forEach(sort -> {
            OrderItem orderItem = new OrderItem();
            orderItem.setColumn(sort.getProperty());
            orderItem.setAsc(sort.getDirection().ordinal() == 0);
            list.add(orderItem);
        });

        pagination.setOrders(list);
        return pagination;
    }

    public void setPage(Integer page) {
        if (page != null) {
            this.page = page;
        }
    }

    public Integer getSize() {
        return size;
    }

    public void setSize(Integer size) {
        if (size != null) {
            this.size = size;
        }
    }

    public List<PageSort> getSorts() {
        return sorts;
    }

    public void setSorts(String[] sorts) {
        if (sorts != null && sorts.length > 0) {
            for (int i = 0; i <= sorts.length - 1; i++) {
                String[] sortStr = sorts[i].split(",");
                String property = sortStr[0];
                String direction = sortStr[1];

                PageSort pageSort = new PageSort();
                pageSort.setProperty(property);
                pageSort.setDirection(Direction.valueOf(direction.toUpperCase()));
                this.sorts.add(pageSort);
            }
        }
    }
}
